 package com.gack.business.service;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import com.gack.business.model.Contacts;
import com.gack.business.model.Message;
import com.gack.business.model.User;
import com.gack.business.model.VideoMessage;
import com.gack.business.model.VideoUser;
import com.gack.business.repository.ContactsRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.UserRepository;
import com.gack.business.repository.VideoMessageRepository;
import com.gack.business.repository.VideoUserRepository;
import com.gack.helper.common.abstractobj.Result;
import com.gack.helper.common.util.SendCode;

/**
 * 
* @ClassName: VideoMessageService.java 
* @Description: 评价controller
* @author Cancerl
* @date 2018年3月21日
*  
 */
@Service
public class VideoMessageService implements VideoMessageServiceInterface {

	@Autowired
	private VideoMessageRepository messageRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private ContactsRepository contactsRepository;
	@Autowired
	private UserRepository uuserRepository;
	@Autowired
	private MessageRepository mmessageRepository;
	@PersistenceContext
	private EntityManager manager;
	
	/**
	 * 获取用户消息
	 */
	@Override
	public Result getUserMessage(String id,Integer currentPage,Integer pageSize) {
		Result result = new Result();
		User user = userRepository.findOne(id);
		if(user != null){
			Sort sort = new Sort(Sort.Direction.DESC, "createtime");
			Pageable pageable = new PageRequest(currentPage, pageSize, sort);
			Page<Message> messages = messageRepository.findByUserid(user.getId(), pageable);
			if(messages != null){
				result.setKey("success");
				result.setValue(messages);
			}else{
				result.setKey("error");
				result.setValue(null);
			}
		}else{
			result.setKey("error");
			result.setMsg("用户不存在，获取用户消息失败");
		}
		return result;
	}

	/**
	 * 添加用户消息
	 * message  添加消息   
	 * type  消息类型  暂定1>>预约消息
	 */
	@Override
	public Result addUserMessage(String id, String message, String type) {
		Result result = new Result();
		/*VideoUser user = userRepository.findOne(id);
		if(user != null){
			try{
				VideoMessage videoMessage = new VideoMessage();
				videoMessage.setMessage(message);
				videoMessage.setType(type);
				videoMessage.setUser(user);
				videoMessage.setCreatetime(new Date());
				messageRepository.save(videoMessage);
				result.setKey("success");
				result.setValue("消息添加成功");
			}catch (Exception e) {
				e.printStackTrace();
				result.setKey("error");
				result.setValue("消息添加失败");
			}
		}else{
			result.setKey("error");
			result.setValue("用户不存在，无法添加用户消息");
		}*/
		return result;
	}
	
	@Override
	@Transactional
	public Result addNewUserMessage(String username,String friendid,String type) {
		Result result = new Result();
		if(type.equals("1")){
			User user = uuserRepository.findUserforUsername(friendid);
			User user1 = uuserRepository.findUserforUsername(username);
		if(user != null){
			/*try{*/
				List<Contacts> contacts=contactsRepository.findContactsforusername(friendid, username);
				if(contacts.size()>0){
					if(contacts.get(0).getType()==1){
						
					}else{
					
					contacts.get(0).setType(0);
					
					}
					contacts.get(0).setFriendAddtime(new Date());
					contactsRepository.save(contacts);
					List<Contacts> ctcs=contactsRepository.findContactsforusername(username, friendid);
					if(ctcs.size()>0){
						 String jpql="delete  from Contacts  u where u.userUsername=:userUsername and u.useridFriendUsername=:useridFriendUsername";
						  Query query2=manager.createQuery(jpql);//
							query2.setParameter("userUsername", friendid);
							query2.setParameter("useridFriendUsername", username);
							query2.executeUpdate();
					}
				}else{
				Contacts cts=new Contacts();
				cts.setUserUsername(username);//发起人
				cts.setUseridFriendId(user.getId());//接受的人
				cts.setFriendAddtime(new Date());
				cts.setType(0);
				cts.setUseridFriendUsername(friendid);
				cts.setUserUserid(user1.getId());
				contactsRepository.save(cts);
				/*Message message=new Message();
				message.setCreateId(username);
				message.setTitle("验证消息");
				message.setMessage("邀请加入");
				message.setMesType(2);
				message.setSendWay(2);
				message.setUserid(user.getId());
				message.setCreatetime(new Date());
				mmessageRepository.save(message );*/
				}
				result.setKey("success");
				result.setValue("好友请求已发送");
			/*}catch (Exception e) {
				e.printStackTrace();
				result.setKey("error");
				result.setValue("消息添加失败");
			}*/
		}else{
			result.setKey("error");
			result.setValue("用户不存在，无法添加用户消息");
		}
			
		}else if(type.equals("2")){
			User user = uuserRepository.findUserforUsername(friendid);
			User user1 = uuserRepository.findUserforUsername(username);
			if(user != null){
				/*try{*/
					List<Contacts> contacts=contactsRepository.findContactsforusername(friendid, username);
					if(contacts.size()>0){
						if(contacts.get(0).getType()==1){
							
						}else{
							contacts.get(0).setType(0);	
						}
						contacts.get(0).setFriendAddtime(new Date());
						
						contactsRepository.save(contacts);
						List<Contacts> ctcs=contactsRepository.findContactsforusername(username, friendid);
						if(ctcs.size()>0){
							 String jpql="delete  from Contacts  u where u.userUsername=:userUsername and u.useridFriendUsername=:useridFriendUsername";
							  Query query2=manager.createQuery(jpql);//
								query2.setParameter("userUsername", friendid);
								query2.setParameter("useridFriendUsername", username);
								query2.executeUpdate();
						}
					}else{
					Contacts cts=new Contacts();
					cts.setUserUsername(username);//发起人
					cts.setUseridFriendId(user.getId());//接受的人
					cts.setFriendAddtime(new Date());
					cts.setType(0);
					cts.setUseridFriendUsername(friendid);
					cts.setUserUserid(user1.getId());
					contactsRepository.save(cts);
					/*Message message=new Message();
					message.setCreateId(username);
					message.setMessage("邀请加入");
					message.setMesType(2);
					message.setSendWay(2);
					message.setUserid(user.getId());
					message.setCreatetime(new Date());
					mmessageRepository.save(message);*/
					}
					result.setKey("success");
					result.setValue("好友请求已发送");
				/*}catch (Exception e) {
					e.printStackTrace();
					result.setKey("error");
					result.setValue("消息添加失败");
				}*/
			}else{
				//发短信
				String message="<font color=#52ADFF>"+username+"</font>"+"邀请"+friendid+"下载i商务app,请点击下载链接";
				String duanMessage=user1.getNickname()+"加您为好友,下载地址:https://www.gack.citic/h5/wordServer/share.html,完成i商务账号注册";
				try {
					SendCode.sendMessage(friendid, duanMessage);
					} catch (Exception e) {
					// TODO Auto-generated catch bloc
					e.printStackTrace();
					result.setKey("error");
					result.setValue("短信发送失败");
				}
					Message msge=new Message();
					msge.setCreateId(username);
					msge.setMessage(message);
					msge.setMesType(2);
					msge.setSendWay(2);
					msge.setUserid(friendid);
					msge.setCreatetime(new Date());
					mmessageRepository.save(msge);
					List<Contacts> contacts=contactsRepository.findContactsforusername(friendid, username);
					if(contacts.size()!=0){
						contacts.get(0).setFriendAddtime(new Date());
						contacts.get(0).setType(0);
						contactsRepository.save(contacts);
					}else{
					Contacts cts=new Contacts();
					cts.setUserUsername(username);//发起人
					
					cts.setFriendAddtime(new Date());
					cts.setType(3);
					cts.setUseridFriendUsername(friendid);
					
					contactsRepository.save(cts);
					}
					result.setKey("success");
					result.setValue("好友请求已发送");
				
			}
			
		}
		return result;
	}
/**
 * username 登录人手机号(受邀)
 * friendid friendid 邀请人手机号(发起人)
 */
	@Override
	@Transactional
	public Result updateNewUserMessage(String username,String friendid,String  status) {
		// TODO Auto-generated method stub
		Result result = new Result();
		User userr=uuserRepository.findUserforUsername(friendid);
		List<Contacts> contacts=contactsRepository.findContactsforusername(username, friendid);
		if(contacts.size()>0){
			/*if(contacts.size()<=1){*/
		/*messageRepository.save(videoMessage);*/
		if(status.equals("1")){//确认 
			/*try{*/
			if(contacts.get(0).getType()!=0){
				contacts.get(0).setFriendPasstime(new Date());
				result.setKey("error");
				result.setValue("请不要重复操作");
			}else{
				contacts.get(0).setType(1);
				contacts.get(0).setFriendPasstime(new Date());
				contactsRepository.save(contacts);
				result.setKey("success");
				result.setValue("成功");
			}
			
			/*contacts.get(0).setType(1);
			contacts.get(0).setFriendPasstime(new Date());
			contactsRepository.save(contacts);*/
			User user1 = uuserRepository.findUserforUsername(username);
			if(!username.equals(friendid)){
				List<Contacts> cots=contactsRepository.findContactsforusername(friendid, username);
				if(cots.size()>0){
					if(cots.get(0).getType()!=0){
						cots.get(0).setFriendPasstime(new Date());
						result.setKey("error");
						result.setValue("请不要重复操作");
					}else{
						cots.get(0).setType(1);
						cots.get(0).setFriendPasstime(new Date());
						contactsRepository.save(cots);
						result.setKey("success");
						result.setValue("成功");
					}
					
					
				}else{
					Contacts cts=new Contacts();
					/*User user = uuserRepository.findOne(friendid);*/
					cts.setUserUsername(username);//发起人
					
					cts.setUseridFriendId(userr.getId());//接受的人
					
					cts.setUseridFriendUsername(friendid);
					
					cts.setUserUserid(user1.getId());
					cts.setFriendAddtime(new Date());
					cts.setType(1);
					cts.setFriendPasstime(new Date());
					contactsRepository.save(cts);
					Message message=new Message();
					message.setCreateId(username);
					message.setMessage("您已成功添加好友"+user1.getNickname()+"("+user1.getUsername()+")");
					message.setTitle("消息提醒");
					message.setState(1);
					message.setMesType(2);
					message.setSendWay(2);
					message.setUserid(userr.getId());
					message.setCreatetime(new Date());
					mmessageRepository.save(message);
					result.setKey("success");
					result.setValue("成功");
					
				}
			
			}
			
			
			/*}catch(Exception e){
				e.printStackTrace();
				result.setKey("error");
				result.setValue("确认失败");
			}*/
		}else if(status.equals("2")){//忽略
			/*try{*/
			if(contacts.get(0).getType()!=0){
				contacts.get(0).setFriendPasstime(new Date());
				result.setKey("error");
				result.setValue("请不要重复操作");
			}else{
				contacts.get(0).setType(2);
				contacts.get(0).setFriendPasstime(new Date());
				contactsRepository.save(contacts);
				result.setKey("success");
				result.setValue("成功");
			}
			/*contacts.get(0).setType(2);
			contacts.get(0).setFriendPasstime(new Date());
			contactsRepository.save(contacts);
			result.setKey("success");
			result.setValue("成功");*/
			if(!username.equals(friendid)){
				List<Contacts> cots=contactsRepository.findContactsforusername(friendid, username);
				if(cots.size()>0){
					if(cots.get(0).getType()!=0){
						cots.get(0).setFriendPasstime(new Date());
						result.setKey("error");
						result.setValue("请不要重复操作");
					}else{
						cots.get(0).setType(2);
						cots.get(0).setFriendPasstime(new Date());
						contactsRepository.save(cots);
						result.setKey("success");
						result.setValue("成功");
					}
					
					
				}
			
			}
			/*Message message=new Message();
			message.setCreateId(username);
			message.setMessage("拒绝");
			message.setTitle("消息验证");
			message.setState(0);
			message.setMesType(2);
			message.setSendWay(2);
			message.setUserid(userr.getId());
			message.setCreatetime(new Date());
			mmessageRepository.save(message);*/
			/*result.setKey("success");
			result.setValue("成功");*/
			/*}catch(Exception e){
				e.printStackTrace();
				result.setKey("error");
				result.setValue("忽略失败");
			}*/
		
			/*}else{
				result.setKey("error");
				result.setValue("请不要重复操作");
			}*/
		}
		}
		return result;
	}
	

	}




